package com.goalias.config;



import cn.hutool.core.exceptions.InvocationTargetRuntimeException;
import com.goalias.exception.BizException;
import com.goalias.exception.ExceptionEnum;
import com.goalias.resp.Result;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class WebException {

    Logger logger = LoggerFactory.getLogger(WebException.class);

    @ExceptionHandler(value = BizException.class)
    public Result bizExceptionHandler(BizException e){
        logger.error("goalias业务异常!原因是:{}",e.getErrorMsg(),e);
        return Result.error(e.getErrorCode(),e.getErrorMsg());
    }

    @ExceptionHandler(value =NullPointerException.class)
    public Result nullPointerExceptionHandler(HttpServletRequest req, NullPointerException e){
        logger.error("发生空指针异常！原因是:{}",e.getMessage(),e);
        return Result.error(ExceptionEnum.OBJECT_NULL_POINTER);
    }

    @ExceptionHandler(value = BindException.class)
    public Result bindExceptionHandler(HttpServletRequest req, BindException e){
        logger.error("发生校验参数异常！原因是:{}",e.getMessage(),e);
        BindingResult bindingResult = e.getBindingResult();
        // 所有参数异常信息
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        List<String> collect = allErrors.stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
        return Result.error(collect.toString());
    }

    @ExceptionHandler(value = InvocationTargetRuntimeException.class)
    public Result exceptionHandler(HttpServletRequest req, InvocationTargetRuntimeException e){
        if (e.getCause().getCause() instanceof BizException cause){
            return Result.error(cause.getErrorCode(),cause.getErrorMsg());
        }
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(value =Exception.class)
    public Result exceptionHandler(HttpServletRequest req, Exception e){
        logger.error("发生系统异常！原因是:{}",e.getMessage(),e);
        return Result.error(e.getMessage());
    }


}
